/*
This file is part of vlc-remote.

vlc-remote is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

vlc-remote is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with vlc-remote.  If not, see <http://www.gnu.org/licenses/>.
*/
import QtQuick 1.1
import com.meego 1.0
import "common"
import "mediaRemoteFunctions.js" as MediaRemote
import "remoteStatus.js" as RemoteStatus
import "vlcRemote.js" as VlcRemote

Page {
    id: remotesPage
    property string server: ""
    property string serverName: "Not connected"
    tools: menuTools

    Component.onCompleted: {
        screen.allowedOrientations = Screen.Portrait;
        //lockInPortrait = true;
        orientationLock = Screen.Portrait;

        load();
    }

    // JS need to be inside a JS file..
    function save()
    {
    }

    function load()
    {
        //name TEXT, type TEXT, ipAddress TEXT, port TEXT, username TEXT, password TEXT, secured BOOLEAN
        var conns = MediaRemote.loadConnections();
        listModel.clear()
        for (var i = 0; i < conns.length; ++i) {
            listModel.append(conns.item(i));
        }

    }

    Timer {
        id: firstLoadTimer
        interval: 500
        repeat: false
        running: false
        triggeredOnStart: false
        onTriggered: {
            // check for autoloadsetting
            if (autoloadLastConnection && 0 < listView.count) {
                // auto select first item
                listView.currentIndex = 0;
                remotesPage.server = listModel.get(0).ipAddress + ":" + listModel.get(0).port;
                remotesPage.serverName= listModel.get(0).name;
                MediaRemote.timestampConnection(listModel.get(0).name);
                try {
                    homeDirectory = MediaRemote.loadSetting("homeDirectory", remotesPage.serverName).item(0).textField;
                }
                catch (e) {
                    console.debug("ERROR: " + e);
                    homeDirectory = "~/";
                }
                browsePage.currentDir = homeDirectory;
                remotesPage.pageStack.pop();
            }
            if (0 === listView.count) {
                listView.selection = -1;
                dialog.open();
            }
        }
    }

    onVisibleChanged: {
        if (visible) {
            load();
            // check for first load
            if (firstload) {
                firstload = false;
                firstLoadTimer.start();
            }
        }
    }

    ScrollDecoratorStyle {
        id: scrollDecoratorStyle
        inverted: true
    }
    ScrollDecorator {
        flickableItem: listView
        platformStyle: scrollDecoratorStyle
    }
/*
    SectionScrollerStyle {
        id: sectionScrollerStyle
        fontBoldProperty: true
        fontPixelSize: 24
        textColor: "white"
        textColorHighlighted: accentColor
    }
    SectionScroller {
        listView: listView
        platformStyle: sectionScrollerStyle
    }
*/

    ButtonStyle {
        id: vlcButtonStyle
        textColor: "white"
        background: "black"
    }

    PageHeader {
        id: pageHeader
        anchors.top: remotesPage.top
        title: qsTr("Your remotes")
        subtitle: serverName + " @ " + server + ""
        onClicked: { myMenu.close(); pageStack.pop(); }
    }

    ListModel{
        id:listModel
    }

    ListView {
        id: listView
        anchors.fill: parent
        anchors.topMargin: 58
        anchors.bottomMargin: 64
        spacing: 4
        model:listModel
        property int selection: -1
        delegate: ItemDelegate {
            //color: "black"
           // border.width: 0
           // border.color: accentColor
            title: "" + name + ""
            subTitle: "<i>" + type + " @ " + ipAddress + ":" + port + "</i>"
            iconType: "vlc"
            onClicked: {
                listView.selection = index;
                listView.currentIndex = index;
            }
            onDoubleClicked: {
                remotesPage.server = ipAddress + ":" + port;
                remotesPage.serverName = name;
                MediaRemote.timestampConnection(name);
                try {
                    homeDirectory = MediaRemote.loadSetting("homeDirectory", remotesPage.serverName).item(0).textField;
                }
                catch (e) {
                    console.debug("ERROR: " + e);
                    homeDirectory = "~/";
                }
                remotesPage.pageStack.pop();
            }

        }
        highlight: highlight
        highlightFollowsCurrentItem: true
        highlightMoveDuration: 2
    }

    Component {
        id: highlight
        Rectangle {
            color: "black"
            border.width: 2
            border.color: accentColor
            radius:  8
            y: listView.currentItem.y
            Behavior on y {
                SpringAnimation {
                    spring: 2
                    damping: 0.2
                }
            }
        }
    }


    QueryDialog {
        id:dialog
        titleText: qsTr("Connection details")
        acceptButtonText: qsTr("Save details")
        rejectButtonText: qsTr("Close")

        content: Column {
            Row {
                Text {
                    width: 100
                    font.pixelSize: 20
                    color: "white"
                    text: qsTr("Name: ")
                }
                TextField {
                    id: name
                    placeholderText: "Connection Name"
                    text: (-1 < listView.selection) ? listModel.get(listView.selection).name : ""
                }
            }
            Row {
                Text {
                    width: 100
                    font.pixelSize: 20
                    color: "white"
                    text: qsTr("IP: ")
                }
                TextField {
                    id: ipAddress
                    placeholderText: "IP Address"
                    text: (-1 < listView.selection) ? listModel.get(listView.selection).ipAddress : ""
                }
            }
            Row {
                Text {
                    width: 100
                    font.pixelSize: 20
                    color: "white"
                    text: qsTr("Port: ")
                }
                TextField {
                    id: port
                    placeholderText: "8080"
                    text: (-1 < listView.selection) ? listModel.get(listView.selection).port : "8080"
                }
            }
         }
        onAccepted: {
            // Need to validate
            MediaRemote.saveConnection(name.text, "VLC", ipAddress.text, port.text, "", "", false, Math.round(new Date().getTime() / 1000));
            load();
        }


    }

    QueryDialog {
        id: dialogConfirmDelete
        property alias message:  message.text
        titleText: qsTr("Really delete?")
        content:  Text {
            id: message
            width:  parent.width
            wrapMode: "WrapAtWordBoundaryOrAnywhere"
            maximumLineCount: 6
            font.pixelSize: 24
            color: "white"
            text: (-1 < listView.selection) ? qsTr("Do you want to delete the connection information for <b>") + listModel.get(listView.selection).name + "</b>?" : ""
        }
        acceptButtonText: qsTr("Yes, delete it")
        onAccepted: {
            if (-1 < listView.selection) {
                MediaRemote.deleteConnection(listModel.get(listView.selection).name);
            }
            load();
        }
        rejectButtonText: qsTr("No, keep it")
    }


    Rectangle {
        color: "black"
        width: parent.width
        height: controlsRow.height + 16
        anchors.bottom: remotesPage.bottom
        anchors.topMargin: 0
        anchors.bottomMargin: 0

        Row {
            id: controlsRow
            height: 64
            opacity: 100
            spacing: 4
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter

            Button {
                //platformStyle: vlcButtonStyle
                id: btnUse
                enabled: (-1 < listView.selection)
                width: 86
                //text: qsTr("Connect")
                iconSource: (btnUse.enabled) ? "file:///usr/share/themes/blanco/meegotouch/icons/icon-m-toolbar-done-white.png" : "file:///usr/share/themes/blanco/meegotouch/icons/icon-m-toolbar-done-dimmed-white.png"
                onClicked: {
                    if (-1 < listView.selection) {
                        remotesPage.server = listModel.get(listView.selection).ipAddress + ":" + listModel.get(listView.selection).port;
                        remotesPage.serverName= listModel.get(listView.selection).name;
                        MediaRemote.timestampConnection(listModel.get(listView.selection).name);
                        try {
                            homeDirectory = MediaRemote.loadSetting("homeDirectory", remotesPage.serverName).item(0).textField;
                        }
                        catch (e) {
                            console.debug("ERROR: " + e);
                            homeDirectory = "~/";
                        }
                        remotesPage.pageStack.pop();
                    }
                }
            }
            Button {
                //platformStyle: vlcButtonStyle
                id: btnAdd
                enabled: true
                width: 86
                iconSource: (btnAdd.enabled) ? "file:///usr/share/themes/blanco/meegotouch/icons/icon-m-toolbar-add-white.png" : "file:///usr/share/themes/blanco/meegotouch/icons/icon-m-toolbar-add-dimmed-white.png"
                //text: qsTr("Add")
                onClicked: { listView.selection = -1; dialog.open(); }
            }
            Button {
                //platformStyle: vlcButtonStyle
                id: btnEdit
                width: 86
                enabled: (-1 < listView.selection)
                iconSource: (btnEdit.enabled) ? "file:///usr/share/themes/blanco/meegotouch/icons/icon-m-toolbar-edit-white.png" : "file:///usr/share/themes/blanco/meegotouch/icons/icon-m-toolbar-edit-dimmed-white.png"
                //text: qsTr("Edit")
                onClicked: {  if (-1 < listView.selection) dialog.open(); }
            }
            Button {
                //platformStyle: vlcButtonStyle
                id: btnRemove
                width: 86
                enabled: (-1 < listView.selection)
                //text: qsTr("Remove")
                iconSource: (btnRemove.enabled) ? "file:///usr/share/themes/blanco/meegotouch/icons/icon-m-toolbar-delete-white.png" : "file:///usr/share/themes/blanco/meegotouch/icons/icon-m-toolbar-delete-dimmed-white.png"
                onClicked: { if (-1 < listView.selection) { dialogConfirmDelete.open(); } }
            }
        }
    }
}

